package com.zisuyi.game.sdk

import android.app.Application
import android.content.Context
import android.util.Log
import androidx.core.content.pm.PackageInfoCompat
import com.orhanobut.logger.Logger
import com.weilele.mvvm.MvvmConf
import com.weilele.mvvm.gson
import com.weilele.mvvm.sdk.UmengHelper
import com.weilele.mvvm.setMvvmLibOnCreateOkHttpListener
import com.weilele.mvvm.utils.activity.getResBool
import com.weilele.mvvm.utils.activity.getResString
import com.zisuyi.game.sdk.game.GameReceiveMessage
import com.zisuyi.game.sdk.library.BuildConfig
import com.zisuyi.game.sdk.library.R
import com.zisuyi.game.sdk.library.login.IGameLogin
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.internal.readBomAsCharset
import retrofit2.Invocation
import java.util.zip.GZIPInputStream
import java.util.zip.ZipOutputStream

open class GameApp : Application() {
    companion object {
        internal lateinit var app: Application

        /**
         * 登录成功后需要赋值
         */
        var secret: String? = null
    }

    override fun attachBaseContext(base: Context?) {
        MvvmConf.IS_DEBUG = BuildConfig.DEBUG
        super.attachBaseContext(base)
    }

    override fun onCreate() {
        super.onCreate()
        app = this
        UmengHelper.init(getResString(R.string.umneng_app_key).toString())
        setMvvmLibOnCreateOkHttpListener { builder ->
            if (MvvmConf.IS_DEBUG) {
                builder.addInterceptor(::httpRequestLog)
            }
            builder.addInterceptor {
                val oldRequest = it.request()
                if (MvvmConf.IS_DEBUG) {
                    val url = oldRequest.url.toString()
                    val method = oldRequest.method
                    oldRequest.tag(Invocation::class.java)?.arguments()?.forEach {
                        println("------------$url($method)start------------->")
                        println(gson.toJson(it))
                        println("------------$url($method)end------------->")
                    }
                }
                val newRequest = oldRequest.newBuilder()
                    .apply {
                        addHeader(
                            "Version",
                            PackageInfoCompat.getLongVersionCode(GameReceiveMessage.info).toString()
                        )
                        addHeader("Name", GameReceiveMessage.packageName)
                        addHeader("Hash", GameReceiveMessage.hash)
                        if (secret != null) {
                            addHeader("Authorization", "Bearer " + (secret ?: ""))
                        }
                    }
                    .build()
                it.proceed(newRequest)
            }
        }
        //facebook登录/google登录
        if (getResBool(R.bool.enable_google_store) == true) {
            IGameLogin.init(this)
        }
    }

    /**
     * 打印Http请求日志
     */
    private fun httpRequestLog(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val bodyStr = StringBuilder()
        val requestParams = when (val body = request.body) {
            is FormBody -> {
                repeat(body.size) {
                    bodyStr.append(body.encodedName(it))
                    bodyStr.append(":")
                    bodyStr.append(body.encodedValue(it))
                    bodyStr.append(",")
                }
                bodyStr.toString()
            }
            else -> {
                bodyStr.append(body.toString())
                bodyStr.append("\n不是FormBody，不支持打印请求参数").toString()
            }
        }
        val requestLog = "发送请求：${request.url}\n请求参数：${requestParams}\n请求头:\n${request.headers}"
        Log.i("网络请求日志拦截", "--------------------------------------------------------")
        Log.i("网络请求日志拦截", requestLog)
        val startTime = System.nanoTime()
        val response = chain.proceed(request)
        val endTime = System.nanoTime()
        val oldSource = response.body?.source() ?: return response
        oldSource.request(java.lang.Long.MAX_VALUE)
        val buffer = oldSource.buffer.clone()
        val charset =
            buffer.readBomAsCharset(
                response.body?.contentType()?.charset(Charsets.UTF_8) ?: Charsets.UTF_8
            )
        val responseStr = if (
            response.header("Content-Encoding")?.contains("gzip", true) == true ||
            response.header("Accept-Encoding")?.contains("gzip", true) == true
        ) {
            GZIPInputStream(buffer.inputStream()).bufferedReader(charset).readText()
        } else {
            buffer.inputStream().bufferedReader(charset).readText()
        }
        val responseLog = "{\'响应链接\':\'${response.request.url}\'," +
                "\'响应请求头\':\'${response.headers}\'," +
                "\'响应时间\':\'${(endTime - startTime) / 1e6} ms\'," +
                "\'响应数据\':${responseStr}}"

        Log.i("网络请求日志拦截", responseLog)
        Log.i("网络请求日志拦截", "--------------------------------------------------------")

        return response
    }
}